package cn.blogsx.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 事物操作
 */
public class JdbcDemo05 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            connection = JDBCUtils.getConnection();
            //开启事务
            connection.setAutoCommit(false);
            //定义sql
            //alex -500
            String sql1 = "update account set balance = balance - ? where id = ?";
            //hah  +500
            String sql2 = "update account set balance = balance + ? where id = ?";
            pstmt1 = connection.prepareStatement(sql1);
            pstmt1.setInt(1, 500);
            pstmt1.setInt(2, 1);
            pstmt2 = connection.prepareStatement(sql2);
            pstmt2.setInt(1, 500);
            pstmt2.setInt(2, 2);

            pstmt1.executeUpdate();
            //手动制造异常
            int i = 10 / 0;
            pstmt2.executeUpdate();

            //代码运行正常，就提交事务
            connection.commit();

        } catch (Exception e) {
            //发生异常，需要回滚事物

            try {
                if (connection != null) {

                    connection.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JDBCUtils.close(pstmt1, connection);
            JDBCUtils.close(pstmt2, null);
        }
    }
}
